
clear all
set more off

*cd /data2/cedsei/firm/

/* Inputs */ 

local in_ramspanel "/data2/cedsei/firm/rams_ourpop_cleaned"

// Created in A3_dj_not:
local in_yob 	   "/data2/cedsei/firm/yob"
local in_wc 	   "/data2/cedsei/firm/wc"
local in_not 	   "/data2/cedsei/firm/dj_not"

/* Outputs */ 

local out_djl 	   "/data2/cedsei/firm/notificatio_li"

********************************************************************************

clear 
use lopnr_peorgnr lopnr_cfarnr lopnr year manfran mantill tenure cumten ///
if inrange(year,2005,2018) using `in_ramspanel'

merge m:1 lopnr using 			"`in_yob'", keep(3) nogen
merge m:1 lopnr lopnr_peorgnr using 	"`in_wc'" , keep(1 3)  nogen
replace wc = 0 if mi(wc)
merge 1:1 lopnr_peorgnr lopnr year using "`in_not'", keep(1 3) nogen ///
keepusing(list_dat)

gen temp = !mi(list_dat)
egen x = group(lopnr_peorgnr lopnr_cfarnr year wc)
// x is our measure of circuits.
egen nrnot     = total(temp), by(x)
keep if nrnot>0 // No need to attend to those circuits with zero individuals
egen dateatnot = mode(list_dat), by(x)
format dateatnot %td
egen temp2 = median(list_dat), by(x)
format temp2 %td
replace dateatnot = temp2 if mi(dateatnot)
drop temp2 
replace dateatnot = list_dat if !mi(list_dat)

gen tenure_temp = min(mantill,month(dateatnot)) - manfran +1 
replace cumten = cumten - tenure + tenure_temp 
drop tenure_temp 
drop if cumten<=0 

bysort x (cumten): gen lifo_rank= _n 
keep if lifo_rank<=nrnot

gen dateatnot_ym = ym(year(dateatnot),month(dateatnot))
format dateatnot_ym %tm

gen ageatnot = (dateatnot_ym - yob)/12
gen de_jure_lifo = ///
cond(inrange(cumten,0,23),1, ///
cond(inrange(cumten,24,47),2, ///
cond(inrange(cumten,48,71),3, ///
cond(inrange(cumten,72,95),4, ///
cond(inrange(cumten,96,119),5, ///
cond(cumten>=120,6,0))))))
replace de_jure_lifo = 12 if ageatnot>=55 & !mi(ageatnot) & !mi(cumten) & wc==1
replace de_jure_lifo = 1 if ageatnot>=67 & !mi(ageatnot) & !mi(cumten)

keep lopnr lopnr_peorgnr dateatnot_ym de_jure_lifo 
gen anstupp_dat_ym = dateatnot_ym + de_jure_lifo
format anstupp_dat_ym %tm
gen y1 = year(dofm(dateatnot_ym))
gen y2 = year(dofm(anstupp_dat_ym))
gen diff = y2 - y1 + 1
expand diff
bys lopnr_peorgnr lopnr: gen year = y1 + _n - 1
gen manfran_djl = /// 
cond(y1==year, month(dofm(dateatnot_ym)), 1)
gen mantill_djl = ///
cond(y2==year, month(dofm(anstupp_dat_ym)), 12)
keep lopnr lopnr_peorgnr year manfran_djl mantill_djl
gcollapse (min) manfran_djl (max) mantill_djl, by(lopnr lopnr_peorgnr year)
save "`out_djl'", replace



